package com.tanjun.userservice.web.service.role.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.query.QueryMethods;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.tanjun.common.enums.err.DefaultErrCode;
import com.tanjun.common.exception.BizException;
import com.tanjun.common.utils.ConvertUntil;
import com.tanjun.userservice.web.service.input.AdminRoleBo;
import com.tanjun.userservice.web.service.menu.service.BaseAdminRoleMenuService;
import com.tanjun.userservice.web.service.role.entity.BaseAdminRoleEntity;
import com.tanjun.userservice.web.service.role.entity.BaseAdminUserRoleEntity;
import com.tanjun.userservice.web.service.role.entity.table.BaseAdminRoleEntityTableDef;
import com.tanjun.userservice.web.service.role.mapper.BaseAdminRoleMapper;
import com.tanjun.userservice.web.service.role.BaseAdminRoleService;
import com.tanjun.userservice.web.service.role.BaseAdminUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
* @author tanjun
* @description 针对表【base_admin_role(系统管理员角色表)】的数据库操作Service实现
* @createDate 2024-12-03 21:44:43
*/
@Service
public class BaseAdminRoleServiceImpl extends ServiceImpl<BaseAdminRoleMapper, BaseAdminRoleEntity>
    implements BaseAdminRoleService {

    @Autowired
    private BaseAdminUserRoleService baseAdminUserRoleService;
    @Autowired
    private BaseAdminRoleMenuService baseAdminRoleMenuService;

    /**
     * 新增或者修改角色信息
     *
     * @param paramVo
     */
    @Override
    public void saveOrUpdateRole(AdminRoleBo paramVo) {
       //1.判断角色名称或者编码是否重复
        long nameCount=this.count(QueryChain.of(BaseAdminRoleEntity.class)
                .eq(BaseAdminRoleEntity::getRoleName,paramVo.getRoleName())
                .ne(BaseAdminRoleEntity::getRoleId,paramVo.getRoleId(),paramVo.getRoleId()!=null)
        );
        if(nameCount>0){
            throw new BizException("用户名称重复");
        }
        long codeCount=this.count(QueryChain.of(BaseAdminRoleEntity.class)
                .eq(BaseAdminRoleEntity::getRoleCode,paramVo.getRoleCode())
                .ne(BaseAdminRoleEntity::getRoleId,paramVo.getRoleId(),paramVo.getRoleId()!=null)
        );
        if(codeCount>0){
            throw new BizException("用户编码重复");
        }
        BaseAdminRoleEntity role= ConvertUntil.convert(paramVo, BaseAdminRoleEntity.class);
        if(role.getRoleId()==null){
            role.setCreateTime(LocalDateTime.now());
            role.setCreator(paramVo.getOperator());
            this.save(role);
        }
        else {
            role.setUpdateTime(LocalDateTime.now());
            role.setUpdater(paramVo.getOperator());
            this.updateById(role);
        }


    }

    /**
     * 删除角色(同时会删除角色权限信息)
     * @param id 角色id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delRole(Long id) {
        BaseAdminRoleEntity role=this.getById(id);
        if(role==null){
            throw new BizException(DefaultErrCode.NO_DATA);
        }
        if(baseAdminUserRoleService.hasUser(id)){
            throw new BizException("改角色下存在用户,无法删除");
        }

        this.removeById(id);
        baseAdminRoleMenuService.delRoleMenus(id);
    }

    /**
     * 根据id获取角色信息
     *
     * @param roleIdList 角色id列表
     * @return 角色列表
     */
    @Override
    public List<BaseAdminRoleEntity> listRolesByIds(List<Long> roleIdList) {
        if(CollectionUtil.isEmpty(roleIdList)){
            return Collections.emptyList();
        }
        return this.listByIds(roleIdList);
    }

    /**
     * 根据id获取角色信息
     *
     * @param roleId 角色id
     * @return 角色信息
     */
    @Override
    @Cacheable(value = "getRoleById",key = "#roleId")
    public BaseAdminRoleEntity getRoleById(Long roleId) {
        return this.getById(roleId);
    }

    /**
     * 获取用户的角色信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<BaseAdminRoleEntity> listRoles(Long userId) {
        QueryWrapper queryWrapper=QueryWrapper.create()
                .select(QueryMethods.distinct(BaseAdminRoleEntityTableDef.BASE_ADMIN_ROLE_ENTITY.ALL_COLUMNS))
                .from(BaseAdminRoleEntity.class)
                .rightJoin(BaseAdminUserRoleEntity.class)
                .on(BaseAdminRoleEntity::getRoleId,BaseAdminUserRoleEntity::getRoleId)
                .eq(BaseAdminUserRoleEntity::getUserId,userId);
        return this.list(queryWrapper);
    }


}




